﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.AuthorCenter.EntityFrameworkCore;
using mozhi.smarterp.AuthorCenter.OpenIddict.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.AuthorCenter.OpenIddict
{
    public class OpenIddictClientTypeRepository : EfCoreRepository<AuthorCenterDbContext, OpenIddictClientType, Guid>, IOpenIddictClientTypeRepository
    {
        public OpenIddictClientTypeRepository(IDbContextProvider<AuthorCenterDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<OpenIddictClientType> GetAsync(string clientId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var clientType = await dbContext.Set<OpenIddictClientType>().AsNoTracking().Where(x=>x.ClientId == clientId).FirstOrDefaultAsync(cancellationToken);

            return clientType;
        }

        public async Task<int> GetCountAsync(string clientId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<OpenIddictClientType>().AsNoTracking().WhereIf(!clientId.IsNullOrEmpty(), x => x.ClientId == clientId).CountAsync(cancellationToken);

            return count;
        }

        public async Task<List<OpenIddictClientType>> GetListAsync(string sorting = null, int maxResultCount = int.MaxValue, int skipCount = 0, string clientId = null, CancellationToken cancellationToken = default)
        {
            sorting = sorting ?? nameof(OpenIddictClientType.ClientId);

            var dbContext = await GetDbContextAsync();

            var list = await dbContext.Set<OpenIddictClientType>().AsNoTracking()
                .WhereIf(!clientId.IsNullOrEmpty(), x => x.ClientId == clientId)
                .Skip(skipCount * maxResultCount).Take(maxResultCount)
                .OrderBy(x => x.ClientId).ToListAsync();

            return list;

        }
    }
}
